/**
 * @description 
 * 
 * Copyright (c) 2015-2017 chengxin,Inc.All Rights Reserved.
 */
package com.vcredit.creditcat.manager.report;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.vcredit.bird.service.report.CustomerQualificationService;
import com.vcredit.creditcat.api.ICreditAussureTaskResultManager;
import com.vcredit.creditcat.model.AuthIdentity;
import com.vcredit.creditcat.model.AuthProccess;
import com.vcredit.creditcat.model.CreditAssure;
import com.vcredit.creditcat.model.CustQualificationStatistics;
import com.vcredit.creditcat.service.AuthIdentityService;
import com.vcredit.creditcat.service.AuthProccessService;
import com.vcredit.creditcat.service.CreditAssureService;
import com.vcredit.creditcat.service.CustQualificationStatisticsService;
import com.vcredit.creditcat.util.ConcurrentDateUtil;
import com.vcredit.creditcat.util.Utility;
import com.vcredit.creditcat.vo.custReoprt.CreditCheckReoprtVo;
import com.vcredit.creditcat.vo.custReoprt.CreditResultVo;
import com.vcredit.framework.util.JacksonUtil;

/**
 * 征信总账单拉取 存库
 * 
 * @author chengxin
 *
 */
@Service(protocol = { "protocol1" }, version = "1.0")
public class CreditAussureTaskResultManager implements ICreditAussureTaskResultManager {

	@Autowired
	private CreditAssureService creditAssureService;
	@Autowired
	private AuthIdentityService authIdentityService;
	@Autowired
	private CustomerQualificationService customerQualificationService;
	@Autowired
	private AuthProccessService authProccessService;
	@Autowired
	private CustQualificationStatisticsService custQualificationStatisticsService;
	private String boy = "男";
	private static Logger logger = LoggerFactory.getLogger(CreditAussureTaskResultManager.class);

	@Override
	public void saveCustAnalysis(Long custId) throws Exception {
		// TODO Auto-generated method stub
		this.pullbill(custId);
	}

	public void pullbill(Long custId) throws Exception {
		// TODO Auto-generated method stub
		CreditAssure obj = new CreditAssure();

		try {
			List<AuthProccess> processese = authProccessService.findByCustId(custId);
			if (processese.size() > 0) {

				obj.setAssureStatus(7);
				obj.setProcessId(processese.get(0).getProccessId());
				CustQualificationStatistics custcs = new CustQualificationStatistics();

				List<CreditAssure> creditAssure = creditAssureService.find(obj);

				// 待拉取的征信
				logger.info("征信报表拉取 开始，待拉取条数" + creditAssure.size());
				if (creditAssure.size() > 0) {

					for (CreditAssure creditAssure2 : creditAssure) {
						if (ConcurrentDateUtil.getNowDate()
								.before(ConcurrentDateUtil.getDateTime(creditAssure2.getExpiredTime()))) {
							custcs = new CustQualificationStatistics();
							// 获取身份证号
							AuthIdentity authIdentity = authIdentityService
									.findByProcessId(creditAssure2.getProcessId());
							// 测试服垃圾数据过滤
							if (null == authIdentity) {
								continue;
							}
							if (StringUtils.isBlank(authIdentity.getCitizenId())) {
								continue;
							}
							if (StringUtils.isBlank(authIdentity.getGender())) {
								continue;
							}
							if (StringUtils.isBlank(creditAssure2.getReportId())) {
								continue;
							}
							// 拼装参数
							Map<String, Object> map = new HashMap<String, Object>();
							map.put("IdentityNo", authIdentity.getCitizenId());
							map.put("ReportId", creditAssure2.getReportId());
							// 产品固定参数
							map.put("ReportType", "10");
							map.put("VbCols", "all");
							logger.info("入参参数：idCard" + authIdentity.getCitizenId() + " ReportId:"
									+ creditAssure2.getReportId());
							// 查询个人征信
							Object resultObj = customerQualificationService.pullbill(map);
							CreditCheckReoprtVo creditCheckVo = JacksonUtil.Json2Obj(resultObj.toString(),
									new TypeReference<CreditCheckReoprtVo>() {
									});
							String results = creditCheckVo.getResult().toString();
							AuthProccess process = authProccessService.findById(creditAssure2.getProcessId());
							Map<String, Object> jsonObj = (Map<String, Object>) JSONObject.parse(results);
							for (Object resultvo : jsonObj.entrySet()) {
								String key = (String) ((Map.Entry) resultvo).getKey();
								Object value = (((Map.Entry) resultvo).getValue());
								custcs = this.custQ(custcs, key, value);
							}
							if (null != custcs) {
								custcs.setCustId(process.getCustId());
								/** 0 男 1 女 **/
								if (boy.equals(authIdentity.getGender())) {
								} else {
									custcs.setSex(1);
								}
								custcs.setCreditExpiredTime(ConcurrentDateUtil.strToDate(creditAssure2.getExpiredTime()));
								CustQualificationStatistics custQualification = new CustQualificationStatistics();
								custQualification.setCustId(process.getCustId());
								List<CustQualificationStatistics> custQualist = custQualificationStatisticsService
										.find(custQualification);
								if (custQualist.size() > 0) {
									if (ConcurrentDateUtil.getDateTime(creditAssure2.getExpiredTime())
											.after(custQualist.get(0).getCreditExpiredTime())) {
										custcs.setCustStatisticsId(custQualist.get(0).getCustStatisticsId());
										custQualificationStatisticsService.update(custcs);
									}
								} else {
									custQualificationStatisticsService.insert(custcs);
								}
							}

						}
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("拉取征信失败", e.getMessage());
			e.printStackTrace();
		}
	}

	public CustQualificationStatistics custQ(CustQualificationStatistics custcs, String key, Object value) {
		// key value.toString() 形式存放
		/** [征信]逾期账户数 **/
		if (CreditResultVo.Loan_Delay_Cnt.equals(key)) {
			custcs.setLoanDelayCnt(Integer.parseInt(value.toString().toString()));
		} else if (CreditResultVo.L90D_QRY_NUM.equals(key)) {
			/** [征信]近90天信用卡和贷款审批查询次数 **/
			custcs.setLdNinetyQryNum(Integer.parseInt(value.toString()));
		} else
		/** [征信]近24个月信用卡最近逾期1距今月数的最小值 **/
		if (CreditResultVo.CRD_MTH_L24M_RCT_M1_MIN.equals(key)) {
			custcs.setCrdMthLmTwoYearsRctMMin(Integer.parseInt(value.toString()));
		} else
		/** [申请人]学历 **/
		if (CreditResultVo.CREDIT_EDUCATION.equals(key)) {
			custcs.setEducation(value.toString());
		} else
		/** [申请人]婚姻状况 **/
		if (CreditResultVo.CREDIT_MARRIAGE.equals(key)) {
			custcs.setMarriage(value.toString());
		} else
		/** [征信]信用卡24个月最大正常还款次数 **/
		if (CreditResultVo.Credit_Normal_Pay_Max.equals(key)) {
			custcs.setCreditNormalPayMax(Integer.parseInt(value.toString()));
		} else
		/** [征信]近24个月贷款正常还款最大次数 **/
		if (CreditResultVo.L24M_LN_PAYCNT_MAX.equals(key)) {
			custcs.setLmTwoYearsLnPaycntMax(Integer.parseInt(value.toString()));
		} else
		/** [征信]近24个月信用卡最大连续正常还款次数 **/
		if (CreditResultVo.L24M_CRD_COL_PAYCNT_MAX.equals(key)) {
			custcs.setLmTwoYearsCrdColPaycntMax(Integer.parseInt(value.toString()));
		} else
		/** [征信]正常卡已使用总额度 **/
		if (CreditResultVo.Normal_Credit_Balance.equals(key)) {
			custcs.setNormUsedSum(Utility.rounding(value.toString()));
		} else
		/** [征信]正常非共享信用卡已使用总额度 **/
		if (CreditResultVo.NORM_CDT_BAL_AVG.equals(key)) {
			custcs.setNormCdtSum(Utility.rounding(value.toString()));
		} else
		/** [征信]当前正常的信用卡已用额度的均值 **/
		if (CreditResultVo.NORM_CDT_BAL_AVG.equals(key)) {
			custcs.setNormCdtBalAvg(Utility.rounding(value.toString()));
		} else
		/** [征信]已用额度大于0的信用卡账户数 **/
		if (CreditResultVo.LST_PAY_DEBT0_ACT_NUM.equals(key)) {
			custcs.setLstPayDebtActNum(Integer.parseInt(value.toString()));
		} else
		/** [征信]过去12个月开户的贷款账户贷款余额与额度之比 **/
		if (CreditResultVo.L12M_LOAN_USEDRATE.equals(key)) {
			custcs.setLmTwoYearsLoanUsedrate(Utility.rounding(value.toString()));
		} else
		/** [征信]评分_当前正常的信用卡账户最大负债额与透支余额之比的均值 **/
		if (CreditResultVo.NORM_CDT_BAL_USED_PCT_AVG.equals(key)) {
			custcs.setNormCdtBalUsedPctAvg(Utility.rounding(value.toString()));
		}
		return custcs;
	}
}
